4. How to reuse code - Functions

  1. Functions
    • Can we list all the functions that we have learned?    input(), print(), str(), int(), float(), len(), random.randint(), random.random(), ...
    • A function is like a code block or a small program that has a name and can be used multiple times. We can define functions in our programs.
    • Here is an example of a function. Let's try it.
      def hello():    # def: a keyword to define a function
          print("Hello!")
      hello()  # Invocation of the function hello(), or calling the function hello()
      hello()
      
    • What if we try to use a function that is defined later? Let's try it.
      hello()
      def hello():
          print("Hello!")
      
    • In the above example, we can see that functions should be defined before they are used.
    • Here is another example of a function that can be used with an argument. Let's try it.
      ??? hello(name):    # name is called a parameter; A value is passed into name when hello() is called.
          print("Hello " + name + "!")
      hello('John')    # 'John' is called an argument here. We may say the argument 'John' is passed to hello().
      name = 'Ruth'
      hello(name)  # The value stored in name is passed to hello().
      
    • In the above example, 'John' is passed to hello() and saved in the variable name inside hello().
    • Functions can return one value, like input(). Here is an example. Any errors? How to fix?
      ??? isEven(num):  # A value is passed into num when isEven() is invoked.
          if num % 2 == 0:
              return True    # The value True is returned, passed back, to the code that calls this function isEven().
          else???
              ??? False
      
      print(isEven(888))    # isEvent(888) is executed, and the result from isEvent(888) is passed to print().
      number = input("Enter an integer: ")
      result = isEven(number)
      print(result)
      
  2. Local and global scopes; local and global variables
    • What if the same variable name is used in a function definition and outside of all functions? Here is an example. Let's try it. The values stored in name and count are changed after the function hello() is called?
      name = 'John';
      count = 1;
      ??? hello(name):
          count = 2;
          name = name * count
          print("Hello " + name + "!")
      hello(name)
      print(name + ", " + count)
      
    • In the above example, the same variable names, name and count, are used in the function hello() and outside of all functions. The variables defined in a function can be used only inside the function. The space where those variables defined in a function is called a local scope. The space outside of all functions is called the global scope. Here are several rules regarding local variables, global variables, and their scopes.
      • Local variables defined in a function, i.e., a local scope, can be used only in the local scope. They cannot be used in any other local scopes or the global scope.
      • Global variables can be read in local scopes.
      • In general, global variables can not be changed in local scopes.
      In this way,
      • A function usually communicates with the outside code through parameters and a return value.
      • Functions have seperate local scopes and they become independent of each other.
      • The global scope is visible in functions. But only reading, not modifing, is allowed in functions.
    • Let's check the next example again. Is the variable count in hello() global or local? Is the variable name in hello() global or local? Let's try the next example.
      name = 'John';
      count = 2;
      ??? hello():
          count = 1;    # count: global variable or local variable?
          print("Hello " + name + "!")    # name: global variable or local variable?
      hello()
      print(name + ", " + str(count))
      
    • What if we really need to modify a global variable in a function? We need to specifically declare which variables are global. Let's read and try the next example.
      name = 'John';
      count = 0;
      def hello(name):
          global count    # count: global variable
          count = count + 1;    # count: global variable or local variable?
          print("Hello " + name + str(count) + "!")
      hello('Ruth')
      hello(name)
      print(count)    # what will be printed?
      
  3. Advanced topics
    • Default values for arguments
    • Keyword arguments
  4. Programming exercises
    1. Write a program that keeps reading integers and checks if they are odd. A function to check if an integer is odd should be defined and used.
    2. Write a function that reads an even integer and returns it. The function should read again if an odd number is read.
    3. Write the function printStars(num) that prints num-many stars. We may need to use print(..., end=''), where end='' makes print() print in the same line.
    4. Write the function printChars(char, num) that prints num-many chars.
    5. Write the function printTriangle(num) that prints a tree of stars. This function can use printStars() or printChars(). E.g., when num is 5,
      *
      **
      ***
      ****
      *****
      
    6. Write a program that reads the size of a triangle and prints the triangle. printTriangle() may be used.
    7. Write a program that reads the size of a triangle and prints the triangle in the following shape.
          *
         **
        ***
       ****
      *****
      
    8. Tic-tac-toe game
      • Write the function that reads a number that should be >= 0 and <= 2.
      • Write the function that prints -+-+-.
    9. 3×3 puzzle game
      • Write the function that reads a number that should be >= 0 and <= 2.
      • Write the function that prints +-+-+-+.
    10. 1-D Mine sweeper game
      • Write the function that makes a string. The length of the string is 10, 3 characters are 'M', and all the other characters are ' '. The position of 'M' should be randomly decided. The function returns the string.
      • Write the function that receives a string and prints the string in the way that all the characters are separated by '|'. E.g., |M|1|0|0|1|M|2|M|1|0| for board = "M1001M2M10".
  5. References